import os
from crontab import CronTab

DIR_PATH = os.path.dirname(os.path.abspath(__file__))
SCRIPT_PATH = os.path.join(DIR_PATH, "test_script.py")


class AutoTiUpdate:
    COMMENT_FLAG = "update_ti"

    def __init__(self, t_mode, t_time):
        self.t_mode = t_mode
        self.t_time = t_time
        self.cron = CronTab(user=True)

    def parse_cron_rule(self):
        if self.t_mode == "hourly":
            return "0 * * * *"
        elif self.t_mode == "minutely":
            return "*/1 * * * *"
        elif self.t_mode == "daily":
            hour, minutes = self.t_time.split(":")
            return "{m} {h} * * *".format(m=minutes, h=hour)
        elif self.t_mode == "weekly":
            week_day, hour, minutes = self.t_time.split(":")
            return "{m} {h} * * {w}".format(m=minutes, h=hour, w=week_day)
        else:
            return None

    def set_cron_task(self):
        rule = self.parse_cron_rule()
        if not rule:
            return

        # clear up
        self.cron.remove_all(comment=AutoTiUpdate.COMMENT_FLAG)
        self.cron.write()

        demo_job = self.cron.new(command='python ' + SCRIPT_PATH, comment=AutoTiUpdate.COMMENT_FLAG)
        demo_job.setall(rule)
        demo_job.enable()
        self.cron.write()
